using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace Tarea20120613
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    /// 
    public enum MapType
    {
        Heightmap,
        Thresholdmap,
        Colormap
    }

    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        KeyboardState oldState;

        Random rnd;

        Texture2D Pixel;
        Texture2D t_height_map;
        Texture2D t_threshhold_map;
        Texture2D t_color_map;

        const int Map_Size = 512;
        byte[,] height_map = new byte[Map_Size + 1, Map_Size + 1];
        byte[,] threshhold_map = new byte[Map_Size + 1, Map_Size + 1];
        Color[,] color_map = new Color[Map_Size + 1, Map_Size + 1];
        //Color

        float roughness = 0.9f;

        MapType currentmap;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
            
            rnd = new Random();
            Pixel = new Texture2D(graphics.GraphicsDevice, 1, 1);
            t_height_map = new Texture2D(graphics.GraphicsDevice, Map_Size + 1, Map_Size + 1);
            t_threshhold_map = new Texture2D(graphics.GraphicsDevice, Map_Size + 1, Map_Size + 1);
            t_color_map = new Texture2D(graphics.GraphicsDevice, Map_Size + 1, Map_Size + 1);
            Color[] col = new Color[1];
            col[0] = Color.White;
            Pixel.SetData<Color>(col);

            height_map[0, 0] = 127;
            height_map[Map_Size, 0] = 127;
            height_map[0, Map_Size] = 127;
            height_map[Map_Size, Map_Size] = 127;

            currentmap = MapType.Heightmap;

            GenerateMaps();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            KeyboardState newState = Keyboard.GetState();

            if (newState.IsKeyDown(Keys.Enter) && !oldState.IsKeyDown(Keys.Enter))
            {
                GenerateMaps();
            }
            if (newState.IsKeyDown(Keys.H) && !oldState.IsKeyDown(Keys.H))
            {
                currentmap = MapType.Heightmap;
            }
            if (newState.IsKeyDown(Keys.T) && !oldState.IsKeyDown(Keys.T))
            {
                currentmap = MapType.Thresholdmap;
            }
            if (newState.IsKeyDown(Keys.C) && !oldState.IsKeyDown(Keys.C))
            {
                currentmap = MapType.Colormap;
            }
            oldState = newState;

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin(SpriteBlendMode.AlphaBlend);

            switch (currentmap)
            {
                case MapType.Heightmap:
                    spriteBatch.Draw(t_height_map, Vector2.Zero, Color.White);
                    break;
                case MapType.Thresholdmap:
                    spriteBatch.Draw(t_threshhold_map, Vector2.Zero, Color.White);
                    break;
                case MapType.Colormap:
                    spriteBatch.Draw(t_color_map, Vector2.Zero, Color.White);
                    break;
            }
                        
            spriteBatch.End();

            base.Draw(gameTime);
        }



        void GenerateHeightMap(int x1, int y1, int w)
        {
            int maxDelta = (int)(w * 127.0f / Map_Size);
            byte delta = (byte)(rnd.Next((int)(-w * roughness), (int)(w * roughness)));
            int tempValue = (int)delta + ((int)height_map[x1, y1] + (int)height_map[x1 + w, y1] + (int)height_map[x1, y1 + w] + (int)height_map[x1 + w, y1 + w]) / 4;

            height_map[x1 + w / 2, y1 + w / 2] = (byte)tempValue;
            height_map[x1 + w / 2, y1] = (byte)((height_map[x1, y1] + height_map[x1 + w, y1]) / 2);
            height_map[x1 + w / 2, y1 + w] = (byte)((height_map[x1, y1 + w] + height_map[x1 + w, y1 + w]) / 2);
            height_map[x1, y1 + w / 2] = (byte)((height_map[x1, y1] + height_map[x1, y1 + w]) / 2);
            height_map[x1 + w, y1 + w / 2] = (byte)((height_map[x1 + w, y1] + height_map[x1 + w, y1 + w]) / 2);


            if (w >= 2)
            {
                GenerateHeightMap(x1, y1, w / 2);
                GenerateHeightMap(x1 + w / 2, y1, w / 2);
                GenerateHeightMap(x1, y1 + w / 2, w / 2);
                GenerateHeightMap(x1 + w / 2, y1 + w / 2, w / 2);
            }
        }

        void GenerateMaps()
        {
            GenerateHeightMap(0, 0, Map_Size);
            GenerateThreshholdMap();
            GenerateColorMap();

            createTexture(height_map, ref t_height_map);
            createTexture(threshhold_map, ref t_threshhold_map);
            createTexture(color_map, ref t_color_map);

        }

        void GenerateThreshholdMap()
        {
            for (int i = 0; i < Map_Size + 1; i++)
            {
                for (int j = 0; j < Map_Size + 1; j++)
                {
                    threshhold_map[i, j] = (byte)(height_map[i, j] > 127 ? 255 : 0);
                }
            }
        }

        void GenerateColorMap()
        {
            for (int i = 0; i < Map_Size + 1; i++)
            {
                for (int j = 0; j < Map_Size + 1; j++)
                {
                    if (height_map[i, j] > 223)
                    {
                        color_map[i, j] = Color.White;
                    }
                    else if (height_map[i, j] > 191)
                    {
                        color_map[i, j] = Color.Yellow;
                    }
                    else if (height_map[i, j] > 159)
                    {
                        color_map[i, j] = Color.Orange;
                    }
                    else if (height_map[i, j] > 127)
                    {
                        color_map[i, j] = Color.DarkOrange;
                    }
                    else if (height_map[i, j] > 95)
                    {
                        color_map[i, j] = Color.Brown;
                    }
                    else if (height_map[i, j] > 63)
                    {
                        color_map[i, j] = Color.Blue;
                    }
                    else if (height_map[i, j] > 31)
                    {
                        color_map[i, j] = Color.DarkBlue;
                    }
                    else
                    {
                        color_map[i, j] = Color.Black;
                    }
                    //color_map[i, j] = (byte)(height_map[i, j] > 127 ? 255 : 0);
                }
            }
        }

        void createTexture(byte[,] source, ref Texture2D destination)
        {
            Color[] colArray = new Color[destination.Width * destination.Width];
            Texture2D tempTex = new Texture2D(graphics.GraphicsDevice, destination.Width, destination.Height);
            int pos = 0;
            for (int i = 0; i < destination.Width; i++)
            {
                for (int j = 0; j < destination.Width; j++)
                {
                    colArray[pos] = new Color(source[i, j], source[i, j], source[i, j]);
                    pos++;
                }
            }
            tempTex.SetData<Color>(colArray);
            destination = tempTex;
        }

        void createTexture(Color[,] source, ref Texture2D destination)
        {
            Color[] colArray = new Color[destination.Width * destination.Width];
            Texture2D tempTex = new Texture2D(graphics.GraphicsDevice, destination.Width, destination.Height);
            int pos = 0;
            for (int i = 0; i < destination.Width; i++)
            {
                for (int j = 0; j < destination.Width; j++)
                {
                    colArray[pos] = source[i, j];
                    pos++;
                }
            }
            tempTex.SetData<Color>(colArray);
            destination = tempTex;
        }


    }
}
